package com.yc.tomcat2;

import com.yc.tomcat2.javax.servlet.YcServlet;
import com.yc.tomcat2.javax.servlet.YcServletContext;
import com.yc.tomcat2.javax.servlet.YcServletRequset;
import com.yc.tomcat2.javax.servlet.YcServletResponse;
import com.yc.tomcat2.javax.servlet.http.YcHttpServletRequest;

import java.io.PrintWriter;

/**
 * @author zwei
 * @create 2024-07-28 19:28
 */
public class DynamicProcessor implements Processor {
    @Override
    public void process(YcServletRequset requset, YcServletResponse response) {
        //requset中的参数已经解析好了
        //1.从request中去requestURI (/hello,到ServletContext的map中去找对应的servlet)
        int contentPathLength = ((YcHttpServletRequest)requset).getContextPath().length();
        String uri = ((YcHttpServletRequest) requset).getRequestURI();
        //uri = uri.substring(contentPathLength);
        YcServlet servlet = null;
        //2.为了保证单例，先看 另一个map中是否已经有了这个class实例 如果有说明时第二次访问 则直接调用service方法
        try {
            if (YcServletContext.servletInstance.containsKey(uri)) {
                servlet = YcServletContext.servletInstance.get(uri);
            } else {
                //3.如果没有则说明是第一次调用  先利用反射创建servlet(调用servlet构造方法)存到另一个map 再调用service方法
                Class clz = YcServletContext.servletClass.get(uri);
                Object obj = clz.newInstance();
                if (obj instanceof YcServlet) {
                    servlet = (YcServlet) obj;
                    servlet.init();
                    YcServletContext.servletInstance.put(uri, servlet);
                }
            }
            servlet.service(requset, response);
        } catch (Exception e){
            String bodyEntity=e.toString();
            String protocol=gen500(bodyEntity);
            //以输出流返回客户端
            PrintWriter out=response.getWriter();
            out.println(protocol);
            out.println(bodyEntity);
            out.flush();
        }

    }
    private String gen500(String bodyEntity) {
        String protocol500="HTTP /1.1 500 Internal Server Error\r\nContent-Type: text/html\r\nContent-length: "+bodyEntity.getBytes().length+"\r\n\r\n";
        return protocol500;
    }
}
